
package com.gw.business.statistics.behavior.controller;

import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gw.business.analysis.model.UserTrackDataAverage;
import com.gw.business.analysis.model.UserTrackDataDetail;
import com.gw.business.analysis.model.UserTrackDataStatistics;
import com.gw.business.analysis.service.UserTrackDataDetailService;
import com.gw.business.common.util.DateUtil;
import com.gw.business.common.util.excel.ConditionCollection;
import com.gw.business.common.util.excel.ExcelOperate;
import com.gw.business.statistics.detailed.model.DetailForm;
import com.gw.platform.controller.DefaultPageController;
import com.gw.platform.page.impl.Page;
import com.gw.platform.util.DateUtils;
import com.gw.platform.util.StringUtils;

/**
 * 统计报表
 * 
 * @author kidy
 * @since 1.0
 * @version 2015年2月4日 kidy
 */

@Controller
@RequestMapping("statisticsDate")
@Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
public class UserTrackDataStatisticsController extends DefaultPageController {
    
    final static Logger logger = Logger.getLogger(UserTrackDataStatisticsController.class);
    
    @Resource
    private UserTrackDataDetailService userTrackDataDetailService;
    
    private ExcelOperate excelOperate;
    
    /**
     * 用户行为列表
     * 
     * @return
     */
    @RequestMapping("/page")
    public String queryUserStatsic() {
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("numPerPage");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String defStartTime = request.getParameter("defStartTime");
        String defEndTime = request.getParameter("defEndTime");
        String temp = request.getParameter("temp");
        if (StringUtils.isEmpty(pageNum)) {
            pageNum = "1";
            pageSize = Page.DEFAULT_PAGE_SIZE + "";
            
        }
     // 设置当前页
        setCurrent(Long.parseLong(pageNum));
        if (temp == null) {
            startTime = DateUtil.getDateFormat(DateUtil.addMonths(new Date(), -1), "yyyy-MM-dd");
            endTime = DateUtil.getDateFormat(new Date(), "yyyy-MM-dd");
            defStartTime=startTime;
            defEndTime=endTime;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (startTime != null && startTime != "") {
            map.put("startTime", startTime);
            
        }
        if (endTime != null && endTime != "") {
            map.put("endTime", endTime);
            
        }
        // 查询用户列表
        page =
            defaultService.page("queryUserTrackDataStatistics", "queryUserTrackDataStatisticsCount", getCurrent(), map, Integer.parseInt(pageSize));
        UserTrackDataStatistics statisc = (UserTrackDataStatistics) defaultService.load("queryUserUtmcmdTotal", map);
        if (null == statisc) {
            statisc = new UserTrackDataStatistics();
        }
        request.setAttribute("page", page);
        request.setAttribute("startTime", startTime);
        request.setAttribute("endTime", endTime);
        request.setAttribute("defStartTime", defStartTime);
        request.setAttribute("defEndTime", defEndTime);
        request.setAttribute("statisc", statisc);
        return "statisc/behaviorStatisc/userBehavorStatiscPage";
    }
    
    /**
     * 导出
     * 
     * @param req
     * @param response
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping("/export")
    public void export(HttpServletRequest req, HttpServletResponse response, DetailForm detailForm) {
        OutputStream out = null;
        try {
            String fileName = "用户行为列表";
            String fileName2 = new String(fileName.getBytes("gb2312"), "iso-8859-1");
            // 文件名
            response.setContentType("application/vnd.ms-excel");// 定义输出类型
            response.setHeader("content-disposition", "attachment;filename=" + fileName2 + ".xls");
            
            String pageNum = request.getParameter("pageNum");
            String pageSize = request.getParameter("numPerPage");
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";
                pageSize = Page.DEFAULT_PAGE_SIZE + "";
                
            }
         // 设置当前页
            setCurrent(Long.parseLong(pageNum));
            Map<String, Object> map = new HashMap<String, Object>();
            if (startTime != null && startTime != "") {
                map.put("startTime", startTime);
                
            }
            if (endTime != null && endTime != "") {
                map.put("endTime", endTime);
                
            }
            // 查询用户列表
            page =
                defaultService.page("queryUserTrackDataStatistics", "queryUserTrackDataStatisticsCount", getCurrent(), map,
                    Integer.parseInt(pageSize));
            excelOperate = new ExcelOperate();
            excelOperate.setDataList((List<UserTrackDataDetail>) page.getData());
            excelOperate.setThAndFieldMap(ConditionCollection.getUserBehavorStaticTHFieldMap());
            excelOperate.excelExportTemp(out, response);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
            } catch (Exception e2) {
                
            }
        }
        
    }
    
    /**
     * 用户详情页面
     * 
     * @return
     */
    @RequestMapping("/accountDetail")
    public String accountDetail() {
        try {
            String pageNum = request.getParameter("pageNum");
            String pageSize = request.getParameter("numPerPage");
            String time = request.getParameter("time");
           
            String beforeMonth=DateUtil.getDateFormat(DateUtil.addMonths(DateUtils.stringToDate(time,"yyyy-MM"), -1), "yyyy-MM");
            // flag 字段标示是，查看的那个账户开户的详情 1：模拟开户 2：真实开户 3：首次入金
            String flag = request.getParameter("flag");
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";
                pageSize = Page.DEFAULT_PAGE_SIZE + "";
                
            }
         // 设置当前页
            setCurrent(Long.parseLong(pageNum));
            Map<String, Object> map = new HashMap<String, Object>();
            if (time != null && time != "") {
                map.put("time", time);
            }
            if (flag != null && flag != "") {
                map.put("flag", flag);
            }
            // 查询用户行为统计
            page = defaultService.page("queryUserDetailStatistics", "queryUserDetailStatisticsCount", getCurrent(), map, Integer.parseInt(pageSize));
            List<UserTrackDataStatistics> staticList = (List<UserTrackDataStatistics>) page.getResult();
            for (UserTrackDataStatistics userTrackDataStatistics : staticList) {
                if (null != userTrackDataStatistics.getUtmcmd() && userTrackDataStatistics.getUtmcmd() != "") {
                    map.put("utmcmd", userTrackDataStatistics.getUtmcmd());
                    map.put("beforeMonth", beforeMonth);
                    List<UserTrackDataAverage> avgList = (List<UserTrackDataAverage>) defaultService.find("queryUserTrackAverage", map);
                    if (null != avgList&&avgList.size()>0) {
                        
                        UserTrackDataAverage avgTemp = avgList.get(0);
                        if (flag.equals("1")) {
                            userTrackDataStatistics.setAvgNum(avgTemp.getDemoCountAverage());
                        } else if (flag.equals("2")) {
                            userTrackDataStatistics.setAvgNum(avgTemp.getRealCountAverage());
                        } else if (flag.equals("3")) {
                            userTrackDataStatistics.setAvgNum(avgTemp.getDepositCountAverage());
                        }
                    }
                }
            }
            request.setAttribute("page", page);
            request.setAttribute("time", time);
            request.setAttribute("flag", flag);
        } catch (Exception e) {
            logger.error("accountDetail exception", e);
        }
        return "statisc/behaviorStatisc/userBehavorDetail";
        
    }
    
    /**
     * 导出
     * 
     * @param req
     * @param response
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping("/staticExport")
    public void detailExport(HttpServletResponse response) {
        OutputStream out = null;
        try {
            String pageNum = request.getParameter("pageNum");
            String pageSize = request.getParameter("numPerPage");
            String time = request.getParameter("time");
            String beforeMonth=DateUtil.getDateFormat(DateUtil.addMonths(DateUtils.stringToDate(time,"yyyy-MM"), -1), "yyyy-MM");
            String flag = request.getParameter("flag");
            String fileName = "详细列表";
            String fileName2 = new String(fileName.getBytes("gb2312"), "iso-8859-1");
            // 文件名
            response.setContentType("application/vnd.ms-excel");// 定义输出类型
            response.setHeader("content-disposition", "attachment;filename=" + fileName2 + ".xls");
            
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";
                pageSize = Page.DEFAULT_PAGE_SIZE + "";
                
            }
         // 设置当前页
            setCurrent(Long.parseLong(pageNum));
            Map<String, Object> map = new HashMap<String, Object>();
            if (time != null && time != "") {
                map.put("time", time);
                
            }
            if (flag != null && flag != "") {
                map.put("flag", flag);
            }
            // 查询用户 用户行为统计
            page = defaultService.page("queryUserDetailStatistics", "queryUserDetailStatisticsCount", getCurrent(), map, Integer.parseInt(pageSize));
            List<UserTrackDataStatistics> staticList = (List<UserTrackDataStatistics>) page.getResult();
            for (UserTrackDataStatistics userTrackDataStatistics : staticList) {
                if (null != userTrackDataStatistics.getUtmcmd() && userTrackDataStatistics.getUtmcmd() != "") {
                    map.put("utmcmd", userTrackDataStatistics.getUtmcmd());
                    map.put("beforeMonth", beforeMonth);
                    List<UserTrackDataAverage> avgList = (List<UserTrackDataAverage>) defaultService.find("queryUserTrackAverage", map);
                    if (null != avgList&&avgList.size()>0) {
                        
                        UserTrackDataAverage avgTemp = avgList.get(0);
                        if (flag.equals("1")) {
                            userTrackDataStatistics.setAvgNum(avgTemp.getDemoCountAverage());
                        } else if (flag.equals("2")) {
                            userTrackDataStatistics.setAvgNum(avgTemp.getRealCountAverage());
                        } else if (flag.equals("3")) {
                            userTrackDataStatistics.setAvgNum(avgTemp.getDepositCountAverage());
                        }
                    }
                }
            }
            excelOperate = new ExcelOperate();
            excelOperate.setDataList((List<UserTrackDataDetail>) page.getData());
            excelOperate.setThAndFieldMap(ConditionCollection.getUserBehavorDetailTHFieldMap(flag));
            excelOperate.excelExportTemp(out, response);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
            } catch (Exception e2) {
                
            }
        }
        
    }
    
    /**
     * 详情列表
     * 
     * @return
     */
    @RequestMapping("/queryUtmcmd")
    public String queryUserUtmcmdStatisc() {
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("numPerPage");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String defauStartTime = request.getParameter("defauStartTime");
        String defauEndTime = request.getParameter("defauEndTime");
        String utmcmd = request.getParameter("utmcmd");
        String utmcsr = request.getParameter("utmcsr");
        String temp = request.getParameter("temp");
        String flag = request.getParameter("flag");
        if (StringUtils.isEmpty(pageNum)) {
            pageNum = "1";
            pageSize = Page.DEFAULT_PAGE_SIZE + "";
            
        }
     // 设置当前页
        setCurrent(Long.parseLong(pageNum));
        Map<String, Object> map = new HashMap<String, Object>();
        if (temp == null) {
            
            startTime = DateUtil.getDateFormat(DateUtil.getBeforeDay(new Date(), 1), "yyyy-MM-dd");
            endTime = DateUtil.getDateFormat(DateUtil.getBeforeDay(new Date(), 1), "yyyy-MM-dd");
            defauStartTime=startTime;
            defauEndTime=endTime;
        }
        if (startTime != null && startTime != "") {
            map.put("startTime", startTime);
            
        }
        
        if (endTime != null && endTime != "") {
            map.put("endTime", endTime);
            
        }
        if (utmcmd != null && utmcmd != "") {
            map.put("utmcmd", utmcmd);
            
        }
        if (utmcsr != null && utmcsr != "") {
            map.put("utmcsr", utmcsr);
            
        }
        // 查询用户列表
        page =
            defaultService.page("queryUserUtmcmdDateStatistics", "queryUserUtmcmdDateStatisticsCount", getCurrent(), map, Integer.parseInt(pageSize));
        UserTrackDataStatistics statisc = (UserTrackDataStatistics) defaultService.load("queryUserUtmcmdTotal", map);
        if (null == statisc) {
            statisc = new UserTrackDataStatistics();
        }
        request.setAttribute("page", page);
        request.setAttribute("startTime", startTime);
        request.setAttribute("flag", flag);
        request.setAttribute("endTime", endTime);
        request.setAttribute("defauStartTime", defauStartTime);
        request.setAttribute("defauEndTime", defauEndTime);
        request.setAttribute("utmcmd", utmcmd);
        request.setAttribute("utmcsr", utmcsr);
        request.setAttribute("statisc", statisc);
        return "statisc/behaviorStatisc/userUtmcmdStatiscPage";
    }
    
    /**
     * 详情列表
     * 
     * @return
     */
    @RequestMapping("/utmDetail")
    public String queryDetail(DetailForm detailForm) {
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("numPerPage");
        String utmcsrs = request.getParameter("utmcsrs");
        String utmcmds = request.getParameter("utmcmds");
        String beginTime = request.getParameter("beginTimes");
        String behaviorTypes = request.getParameter("behaviorTypes");
        
        String ut = request.getParameter("ut");
        if (StringUtils.isEmpty(pageNum)) {
            pageNum = "1";
            pageSize = Page.DEFAULT_PAGE_SIZE + "";
            
        }
        if (ut == null ) {
            detailForm = new DetailForm();
            detailForm.setUtmcsr(utmcsrs);
            detailForm.setUtmcmd(utmcmds);
            detailForm.setBehaviorType(behaviorTypes);
            detailForm.setBeginTime(beginTime);
            detailForm.setEnTime(beginTime);
        }
        
        // 查询用户列表
        Page pageData = userTrackDataDetailService.queryUserList(detailForm, pageNum, pageSize);
        request.setAttribute("page", pageData);
        request.setAttribute("UtmForm", detailForm);
        
        return "statisc/behaviorStatisc/utmDetail";
    }
    
    /**
     * 导出
     * 
     * @param req
     * @param response
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping("/utmcmdExport")
    public void queryUtmcmdExport(HttpServletRequest req, HttpServletResponse response, DetailForm detailForm) {
        OutputStream out = null;
        try {
            String fileName = "来源媒介统计列表";
            String fileName2 = new String(fileName.getBytes("gb2312"), "iso-8859-1");
            // 文件名
            response.setContentType("application/vnd.ms-excel");// 定义输出类型
            response.setHeader("content-disposition", "attachment;filename=" + fileName2 + ".xls");
            
            String pageNum = request.getParameter("pageNum");
            String pageSize = request.getParameter("numPerPage");
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            String utmcmd = request.getParameter("utmcmd");
            String utmcsr = request.getParameter("utmcsr");
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";
                pageSize = Page.DEFAULT_PAGE_SIZE + "";
                
            }
         // 设置当前页
            setCurrent(Long.parseLong(pageNum));
            Map<String, Object> map = new HashMap<String, Object>();
            if (startTime != null && startTime != "") {
                map.put("startTime", startTime);
                
            }
            if (endTime != null && endTime != "") {
                map.put("endTime", endTime);
                
            }
            if (utmcmd != null && utmcmd != "") {
                map.put("utmcmd", utmcmd);
                
            }
            if (utmcsr != null && utmcsr != "") {
                map.put("utmcsr", utmcsr);
                
            }
            // 查询用户列表
            page =
                defaultService.page("queryUserUtmcmdDateStatistics", "queryUserUtmcmdDateStatisticsCount", getCurrent(), map,
                    Integer.parseInt(pageSize));
            
            excelOperate = new ExcelOperate();
            excelOperate.setDataList((List<UserTrackDataDetail>) page.getData());
            excelOperate.setThAndFieldMap(ConditionCollection.getAttributionStatiscTHFieldMap());
            excelOperate.excelExportTemp(out, response);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
            } catch (Exception e2) {
                
            }
        }
        
    }
}
